/** @format */

import { USER_CONF } from '../contants/configCont'
import { GiteeService } from '../services/giteeService'
import { buildDefaultUrl } from '../utils/commonUtils'
import { useEnv } from './useEnv'

function formatFile(data) {
  const tp = typeof data
  if (tp === 'object') return data
  if (tp === 'string') return { name: data, path: data }
  return null
}

function formatToArray(data) {
  if (!data) return []
  const tp = typeof data
  if (tp === 'string') return [data]
  if (!Array.isArray(data)) return [data]
  return data
}

const giteeService = new GiteeService()

const getMarkdownFiles = async (
  owner: string,
  repo: string,
  path: string = ''
) => {
  try {
    const response = await giteeService.getDirectoryContents(owner, repo, path)
    const list = response as any[]

    const markdownFiles: any = []

    let directories: any[] = []

    if (path === '') {
      const { isPublish, getEnv } = useEnv()

      await getEnv()

      const configFileName =
        isPublish.value && owner === USER_CONF.owner && repo === USER_CONF.repo
          ? 'config-publish.json'
          : 'config.json'

      const configFile = list.find((item) => item.name === configFileName)
      if (configFile) {
        let result: any = await giteeService.getFileContentByUrl(
          configFile.url,
          true
        )

        const { files = [], dirs = [], ...rest } = result.content
        markdownFiles.push(...formatToArray(files).map(formatFile))
        markdownFiles._config = rest

        directories = formatToArray(dirs).map((item) => {
          if (typeof item === 'string') return { path: item }
          return item
        })
      } else {
        const howFileName = isPublish.value ? 'how-publish.json' : 'how.json'
        const howData = await giteeService.getFileContentByUrl(
          buildDefaultUrl(howFileName),
          true
        )
        if (Array.isArray(howData.content)) {
          markdownFiles.push(
            ...howData.content.map((item) => {
              const result = formatFile(item)
              result.url = buildDefaultUrl(result.path)
              return result
            })
          )
        }
      }
    } else {
      const files = list.filter((file: any) => file.name.endsWith('.md'))
      // 排序处理
      const sortList = files.sort((a, b) => {
        const numA = parseInt(a.name, 10) || Number.MAX_SAFE_INTEGER
        const numB = parseInt(b.name, 10) || Number.MAX_SAFE_INTEGER
        return numA - numB
      })
      markdownFiles.push(...sortList)
      directories = list.filter((file: any) => file.type === 'dir')
    }

    // // 递归获取子目录中的 Markdown 文件
    for (const dir of directories) {
      const subFiles = await getMarkdownFiles(owner, repo, dir.path)
      markdownFiles.push({ ...dir, children: subFiles, direction: true })
    }

    return markdownFiles
  } catch (error) {
    console.error('获取 Markdown 文件失败:', error)
    throw error
  }
}

export const useBook = () => {
  return {
    getMarkdownFiles,
  }
}
